package com.wsj.a.collapsingdemo.widget.recycler.recycler;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.LinearLayout;


import java.util.List;

/**
 * ToDo:列表数据加载
 */
public class RecyclerViewDelegate<T> extends RecyclerViewContract.RVPresenter<T> {

    //下拉刷新的布局
    private XRefreshView mRefreshView;
    //列表RecyclerView底部下面的加载更多布局
    private View mLoadingView;
    //分页,从0开始
    private int mPage = 0;
    //每一页的item个数,默认10条
    private int mCount = 10;
    //默认能够下拉刷新
    private boolean mPullRefreshEnabled = true;
    //默认能够加载更多
    private boolean mLoadingMoreEnabled = true;
    //加载分页，第一页之后的哪一个页面没有跟多数据
    private boolean mNoMoreData = false;
    //是否显示更多布局
    private boolean mIsShowLoadingView=true;
    //不用显示底部提示文字
    private boolean mNoBottomText=false;


    public RecyclerViewDelegate(RecyclerViewContract.IFLoadData loadData, RecyclerViewContract.IFAdapter adapter) {
        super(loadData, adapter);
    }

    /**
     * @return
     */
    public static RecyclerViewDelegate with(RecyclerViewContract.IFLoadData L, RecyclerViewContract.IFAdapter F) {
        return new RecyclerViewDelegate(L, F);
    }

    /**
     * 默认的单行列表竖向显示
     *
     * @param refreshView
     * @param recyclerView
     * @return
     */
    public RecyclerViewDelegate recyclerView(XRefreshView refreshView, RecyclerView recyclerView) {
        this.mRefreshView = refreshView;
        initLinearLayoutManager(recyclerView, LinearLayoutManager.VERTICAL);
        return this;
    }

    /**
     * 默认的单行列表竖向显示
     *
     * @param refreshView
     * @param refreshView
     * @param recyclerView
     * @return
     */
    public RecyclerViewDelegate recyclerView(XRefreshView refreshView, RecyclerView recyclerView, StateFulListener listener) {
        this.mRefreshView = refreshView;
        initEmpty(listener);
        initLinearLayoutManager(recyclerView, LinearLayoutManager.VERTICAL);
        return this;
    }


    private void initEmpty(StateFulListener listener) {
        this.mStateFulListener = listener;
    }

    /**
     * 网格布局
     *
     * @param refreshView
     * @param recyclerView
     * @param spanCount    网格布局的格数
     * @return
     */
    public RecyclerViewDelegate recyclerView(XRefreshView refreshView, RecyclerView recyclerView, int spanCount) {
        this.mRefreshView = refreshView;
        initGridLayoutManager(recyclerView, spanCount);
        return this;
    }

    /**
     * 网格布局
     *
     * @param refreshView
     * @param recyclerView
     * @param spanCount    网格布局的格数
     * @return
     */
    public RecyclerViewDelegate recyclerView(XRefreshView refreshView, RecyclerView recyclerView, int spanCount, StateFulListener lisenter) {
        this.mRefreshView = refreshView;
        initEmpty(lisenter);
        initGridLayoutManager(recyclerView, spanCount);
        return this;
    }

    public RecyclerViewDelegate StaggeredGridRecyclerView(XRefreshView refreshView, RecyclerView recyclerView){
        this.mRefreshView = refreshView;
        initStaggeredGridLayoutManager(recyclerView,2, StaggeredGridLayoutManager.VERTICAL);
        return this;
    }

    /**
     * 设置列表加载的布局
     *
     * @param loadingView 自定义的列表底部加载布局
     * @return
     */
    public RecyclerViewDelegate setLoadingView(View loadingView) {
        mLoadingView = loadingView;
        return this;
    }

    public RecyclerViewDelegate isShowLoadingView(boolean isShowLoadingView) {
        mIsShowLoadingView = isShowLoadingView;
        return this;
    }

    /**
     * 设置列表的头部
     *
     * @param headerView
     * @return
     */
    public RecyclerViewDelegate setHeaderView(View headerView) {
        mHeaderView = headerView;
        return this;
    }

    /**
     * 设置列表加载的底部
     *
     * @param footerView
     * @return
     */
    public RecyclerViewDelegate setFooterView(View footerView) {
        mFooterView = footerView;
        return this;
    }

    /**
     * @param pullRefresh 头部是否下拉
     * @param loadingMore 底部加载更多
     * @return
     */
    public RecyclerViewDelegate<T> cancelRefresh(boolean pullRefresh, boolean loadingMore) {
        this.mPullRefreshEnabled = pullRefresh;
        this.mLoadingMoreEnabled = loadingMore;
        return this;
    }

    public RecyclerViewDelegate<T> stateFulListener(StateFulListener listener) {
        initEmpty(listener);
        return this;
    }



    public RecyclerViewDelegate build() {

        initRefreshView();

        mAdapter = new RVAdapter();

        mHeaderViewRecyclerAdapter = new HeaderViewRecyclerAdapter(mAdapter);
        //添加列表头部
        if (mHeaderView != null) {
            mHeaderViewRecyclerAdapter.setHeaderView(mHeaderView);
        }
        //添加列表尾部
        if (this.mFooterView != null) {
            mHeaderViewRecyclerAdapter.setFooterView(mFooterView);
        }

        //需要加载更多的
        initLoadMoreView();

        mRecyclerView.setAdapter(mHeaderViewRecyclerAdapter);
        return this;
    }

    private void initRefreshView() {

        mRefreshView.setPinnedTime(300);
        mRefreshView.setMoveForHorizontal(true);
        mRefreshView.setPullLoadEnable(true);
        mRefreshView.setAutoLoadMore(false);
        mRefreshView.enableReleaseToLoadMore(false);
        mRefreshView.enableRecyclerViewPullUp(true);
        mRefreshView.enablePullUpWhenLoadCompleted(true);
        mRefreshView.setSilenceLoadMore(false);
        mRefreshView.setHideFooterWhenComplete(false);
        mRefreshView.setHeadMoveLargestDistence(200);

        mRefreshView.setPullLoadEnable(mLoadingMoreEnabled);
//        //设置在上拉加载被禁用的情况下，是否允许界面被上拉
        mRefreshView.setMoveFootWhenDisablePullLoadMore(mLoadingMoreEnabled);
//
        mRefreshView.setPullRefreshEnable(mPullRefreshEnabled);
        //设置在下拉刷新被禁用的情况下，是否允许界面被下拉
        mRefreshView.setMoveHeadWhenDisablePullRefresh(mPullRefreshEnabled);

        mRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                super.onRefresh(isPullDown);

                if (isPullDown) {
                    //下拉刷新使用
                    mPage = 0;
                    //初次加载，加载更多的不显示
                    showLoadMoreView(true);
                    mNoMoreData = false;
                    //网络请求数据

                    if (mIFLoadData != null) {
                        mIFLoadData.onRefresh();

                    }
                }
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);

                if (mIFLoadData != null) {
                    mIFLoadData.onLoadMore();
                }
            }
        });
    }

    private void initLoadMoreView() {
        if (mLoadingMoreEnabled) {

            //加载更多的样式
            if (mLoadingView == null) {
                //默认的样式,
                mLoadingView = new LoadingMoreView(mRecyclerView.getContext());
            }

            if (mIsShowLoadingView){
                mHeaderViewRecyclerAdapter.setLoadingView(mLoadingView);
            }
        }
    }

    /**
     * 是否显示更多布局
     */
    public void isShowLoadMoreView(boolean isShow){

        if (mLoadingView!=null){
            if (isShow){
                mLoadingView.setVisibility(View.VISIBLE);
            }else {
                mLoadingView.setVisibility(View.GONE);

            }
        }
    }

    /**
     * 设置页码
     */
    public void setPage(int page) {
        mPage = page;
    }

    /**
     * 下一页,获取数据的时候调用
     *
     * @return
     */
    public int nextPage() {
        return ++mPage;
    }

    /**
     * 下一页,获取当前的分页
     *
     * @return
     */
    public int getPage() {
        return mPage;
    }

    /**
     * 需要显示网络错误页面
     *
     * @return
     */
    public boolean needShowErrorView() {
        return mPage < 1 && getDataList().size() == 0;
    }

    /**
     * 返回每页的条数
     *
     * @return
     */
    public int getPageSize() {
        return mCount;
    }

    /**
     * 重新加载数据
     */
    @Override
    public void reLoadData() {
        //页面一定要设置为初始页
        mPage = 0;

        //网络请求数据
        if (mIFLoadData != null) {
            mIFLoadData.onRefresh();
        }
    }

    //下拉刷新数据（添加到头部）
    @Override
    public void refreshData(List list) {
        //刷新完成,隐藏进度条...
        refreshComplete();

        if (list != null) {
            //首先清空原有数据
            clearData();
            if (list.size() != 0) {
                //有数据的话,清空原来的数据,防止数据重复添加。
                getDataList().addAll(list);
            }
            mAdapter.notifyDataSetChanged();
        }

        //下拉刷新把页面设置为默认
        mPage = 0;
        showEmptyView();
    }


    //上拉时刷新数据,并把新数据添加到头部
    public void addHeaderDataByRefresh(List list){
        refreshComplete();
        if(list!=null){
            getDataList().addAll(0,list);
        }
        mAdapter.notifyDataSetChanged();
        //下拉刷新把页面设置为默认
        showEmptyView();
    }


    @Override
    public void render(List list) {

        //刷新完成,隐藏进度条...
        refreshComplete();
        if (list == null) {
            return;
        }

        //下拉刷新,多次请求首页的话,清空数据
        if (mPage == 1 || mPage == 0) {
            //首先清空原有数据
            clearData();
            if (list.size() != 0) {
                //有数据的话,清空原来的数据,防止数据重复添加。
                getDataList().addAll(list);
            }
            mAdapter.notifyDataSetChanged();
        } else {
            //加入新的数据
            //一定要调用这个方法,因为RecyclerView添加了头部,所以这个position+1
            int position = getDataList().size();
            if (mHeaderView == null) {
                mAdapter.addNewList(position, list);
            } else {
                mAdapter.addNewList(position + 1, list);
            }
        }

        showEmptyView();
        //如果数据为0.把页码回置
        if (list.size() == 0) {
            mPage--;
        }

    }


    //网络连接失败的话需要调用，刷新完成，页码退回
    public void onError() {
        refreshComplete();
        mPage--;
    }

    //刷新完成,隐藏进度条...
    public void refreshComplete() {

        //加载更多
        showLoadMoreView(false);

        mRefreshView.stopRefresh();
        mRefreshView.stopLoadMore();

        showEmptyView();
    }

    //是否显示加载更多的布局
    private void showLoadMoreView(boolean bool) {
        if (mLoadingMoreEnabled) {
            //加载更多的设置
            if (mLoadingView instanceof LoadingMoreView) {

                LoadingMoreView loadingView = (LoadingMoreView) mLoadingView;
                if(mNoBottomText){
                    loadingView.setStatus(LoadingMoreView.STATUS_BOTTOM_TEXT);
                    return;
                }
                if (mNoMoreData) {
                    loadingView.setStatus(LoadingMoreView.STATUS_NO_MORE);
                } else {
                    if (mPage < 1) {
                        loadingView.setStatus(LoadingMoreView.STATUS_INIT);
                    } else {
                        loadingView.setStatus(LoadingMoreView.STATUS_LOADING);
                    }
                }

            } else {
                mLoadingView.setVisibility(View.INVISIBLE);
            }
        }
    }

    //上拉没有更多的数据
    public void setShowNoMoreData(boolean noData) {
        this.mNoMoreData = noData;
    }

    public void setShowNoBottomText(boolean noBottomText){
        this.mNoBottomText=noBottomText;
    }

    @Override
    public void notifyDataSetChanged() {
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
        showEmptyView();
    }

    //查看列表数据
    @Override
    public void showEmptyView() {
        if (mStateFulListener != null) {
            if (getDataList() != null) {
                if (getDataList().size() == 0) {
                    mStateFulListener.showEmptyView();
                } else {
                    mStateFulListener.showContentView();
                }
            } else {
                mStateFulListener.showEmptyView();
            }
        }
    }

    /**
     * 显示网络错误布局
     */
    public void showErrorView() {
        mRefreshView.stopRefresh();
        mRefreshView.stopLoadMore();

        if (mStateFulListener != null) {
            if (getDataList() != null && getDataList().size() > 0) {
                mStateFulListener.showContentView();
            } else {
                mStateFulListener.showErrorView();
            }
        }
    }
}